package com.chixing.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController
public class FileUploadController {
    @PostMapping("uploadSingleFileAjax")
    public String uploadSingleFileAjax(@RequestParam("myimage") MultipartFile multipartFile, HttpServletRequest request){
        String originalFileName = multipartFile.getOriginalFilename();  // a.jpg
        // 重命名
        String fileName =  new Date().getTime()+originalFileName.substring(originalFileName.lastIndexOf("."));
        System.out.println("文件的名称：" + fileName);


        String uploadDirPth =   request.getSession().getServletContext().getRealPath("/upload/");
        System.out.println("文件上传的文件夹是:" + uploadDirPth);
        File file = new File(uploadDirPth);
        if(!file.exists()){
            file.mkdir();
        }

        // 上传 /upload/a.jpg
        String uploadFilePath = uploadDirPth + fileName;
        System.out.println("文件上传的全路径：" + uploadFilePath);
        File uploadFile = new File(uploadFilePath );
        try {
            multipartFile.transferTo(uploadFile);  // 文件上传
            System.out.println("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败");
        }

        String dbImagePath = "/upload/"+fileName;
        // service.saveImg(....)

        return dbImagePath;
    }
}
